package c2.cross.business.guildwar.rank;

import c2.cross.business.base.CrossSubModule;
import c2.cross.business.guildwar.GuildWarModule;
import cate.game.pvp.guildwar.data.GWGuildProfile;
import cate.game.pvp.guildwar.data.rank.GWGuildRank;
import easy.java.dev.note.NoteClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;


@NoteClass("公会战-公会排行榜子模块")
@Slf4j
public class GuildWarGuildRankModule extends CrossSubModule<GuildWarModule> {

    private List<GWGuildRank> list;

    @Override
    public void initDependent() throws Exception {
        super.initDependent();
        this.list = useDb().guildWar.getGuildList();
    }


    @Override
    public void onShutdown() throws Exception {
        super.onShutdown();
        save();
    }

    public List<GWGuildRank> getCopyList(){
        return new ArrayList<>(list);
    }

    public synchronized void clearList() {
        this.list.clear();
    }

    private static final int RANK_MAX = 100;

    public synchronized void record(GWGuildProfile profile, int value) {
        // 是否已经上榜
        GWGuildRank his = findRankByUid(profile.uid);
        if (his != null) {
            his.profile = profile.copy();
        }
        if (list.size() >= RANK_MAX) {
            GWGuildRank last = list.get(list.size() - 1);
            if (last.value > value) {
                // 没有进排行榜
                return;
            }
        }
        if (his != null) {
            his.value = value;
        } else {
            GWGuildRank rank = new GWGuildRank(profile, value);
            if (list.size() >= RANK_MAX) {
                list.remove(list.size() - 1);
            }
            list.add(rank);
        }
        list.sort(Comparator.comparing((GWGuildRank a) -> -a.value).thenComparing(a -> -a.profile.totalPower));
    }

    public GWGuildRank findRankByUid(String uid) {
        try {
            for (GWGuildRank rank : list) {
                if (StringUtils.equals(uid, rank.profile.uid)) {
                    return rank;
                }
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    public int getRankIndex(String uid) {
        try {
            for (int i = 0; i < list.size(); i++) {
                GWGuildRank rank = list.get(i);
                if (StringUtils.equals(rank.profile.uid, uid)) {
                    return i + 1;
                }
            }
            return -1;
        } catch (Exception e) {
            return -1;
        }
    }

    public void save() {
        useDb().guildWar.updateGuildList(list);
    }
}
